;_____________________________________________________________________
;---------------------------------------------------------------------
;	Title: COMPILE and PUBLISH UPDATE
;---------------------------------------------------------------------
;	Group: Overview
;		testing
;		Handles versioning, compiling and publishing of PM App Launcher.
;		
;		Determines the next version number for the PM App Launcher, then 
;		compiles the PM Application Launcher file and the PM
;		Application Launcher Install file, setting both of their versions
;		(as well as the versions listed in the versionCheck.ini file)
;		to the correct, most recent version number. Finally, gives the user
;		a choice to either "publish," which will publish the file to
;		the update server (initiating an update for all users), or to 
;		simply end after compiling the installer.
;
;	Group: How to Use
;		General instructions on calling/using the file.
;
;	Command Line:
;		Can use command line switches shown below to perform the following
;		functions-
;
;		None - If run without parameters, then the project will compile, 
;				increment the version, and prompt to publish
;		-doc - Compile the NaturalDocs documentation for the project, then exit
;		-publish - Simply publish an existing compiled PM App Launcher Update file
;					to the update server
;
;	Normal Use:
;		The same options that are available through command line are available
;		when the script is run normally; the user is presented with a menu that
;		allows choosing how the script will function. If no selection is made,
;		then the script will exit.
;
;---------------------------------------------------------------------
 #NoEnv
 #SingleInstance, Force
 SetWorkingDir, % A_ScriptDir
;_____________________________________________________________________
;---------------------------------------------------------------------



;============================================================================
; 					S C R I P T    S E T T I N G S
;============================================================================
	
	
	;___________________
	; 		PUBLIC FILES
	;
	 EPUB			=	\\corp.halliburton.com\team\WD\Business Development and Technology\General\Engineering Public
	 APPDATA		=	%EPUB%\PM App Launcher\App Data\Internal
	 VER_INI_NAME	=	versioncheck.ini
	 VERSION_INI 	= 	%APPDATA%\%VER_INI_NAME%
	 
	 ;_________________________
	 ; 		BUILD HELPER FILES
	 ;
	 VER_UPDATE		=	%A_ScriptDir%\Include\Version Updater.ahk
	 DUMP_BUILD		=	%A_ScriptDir%\Include\_Dump Build Source.ahk
	
	
	;__________________________________
	; 		COMPILE RESOURCE FILE PATHS
	;
	 PMAL_ICON		=	%A_ScriptDir%\Resource\PML_icon.ico
	 INFILE_ICON	=	%A_ScriptDir%\Resource\PMI_icon.ico
	
	
	;_________________________________________
	; 		PM APPLICATION LAUNCHER FILE PATHS
	;
	 PMAL_INI		=	%A_ScriptDir%\PM Application Launcher.ahk.ini
	 PMAL_AHK		=	%A_ScriptDir%\PM Application Launcher.ahk
	 PMAL			=	%A_ScriptDir%\PM Application Launcher.exe
	
	;_________________________________________________
	; 		PM APPLICATION LAUNCHER INSTALL FILE PATHS
	;
	 INFILE_INI		=	%A_ScriptDir%\PM App Launcher Install.ahk.ini
	 INFILE_AHK		=	%A_ScriptDir%\PM App Launcher Install.ahk
	 INFILE			=	%A_ScriptDir%\PM App Launcher Update.exe
	
	;______________________________
	; 		PUBLISHED FILE SETTINGS
	;
	 PUBLISH_LOC	=	\\ENAUS00072441\PM Apps
	 PUBLISH_NAME	=	PM App Launcher Update.exe
	 PUBLISHED_FILE = 	%PUBLISH_LOC%\%PUBLISH_NAME%
	 
;============================================================================	 
	 
	 
	
		
	
	

;===================================================================================================
;                           		PARAMETER HANDLE
;===================================================================================================
if (%0% > 0){
	Loop %0%
		paramList .= (paramList ? " " : "") %A_Index%
	
	p := param(paramList)
	
	;_________________________________________
	; 		-DOC:  DOCUMENT CODE & EXIT
	;
	if p.doc
		document()
	
	;___________________________________________________
	; 		-PUBLISH:  PUBLISH INSTALLER (W/O COMPILING)
	;
	if p.publish
		goto Publish
}





;=================================================================
;          PROMPT FOR WHAT ACTION TO TAKE (IF NO PARAMETERS)
;=================================================================
ans := custmsgbox("PM App Launcher Builder", "What would you like to do?", "Compile/Build|Publish Existing|Document","Q")

if ans = Compile/Build
	goto, Begin
else if ans = Publish Existing
	goto, publish
else if ans = Document
	document()
else {
	SplashImage, , w240 h95 B1, , `n`nGoodbye!`n, 
	Sleep 1000
	ExitApp
}





Begin:
;=================================================================
;   SET COMPILER RESOURCE FILE PATHS RELATIVE TO CURRENT PATH
;=================================================================

	;________________________________________
	; 		SET VALUES IN PM APP LAUNCHER INI
	;
	IniWrite, %PMAL_ICON%, %PMAL_INI%, VERSION, Resource_Files
	IniWrite, %PMAL_ICON%, %PMAL_INI%, ICONS, Icon_1	

	;______________________________________________
	; 		SET INI VALUES IN PM INSTALLER INI FILE
	;
	IniWrite, %INFILE_ICON%, %INFILE_INI%, VERSION, Resource_Files
	IniWrite, %INFILE_ICON%, %INFILE_INI%, ICONS, Icon_1







;============================================================================
;         COMPILE / BUILD  PM APP LAUNCHER  &  INSTALLER
;============================================================================


	;_____________________________________
	; 	GET CURRENT BUILD VERSION FROM INI
	;
		IniRead, INIVERSION, % VERSION_INI, pm app launcher, version, Error
		If (INIVERSION = "Error"){
			MsgBox, Error while trying to get version from versioncheck.ini...
			ExitApp
		}
		
	
	;_________________________________________________________________
	; 	DETERMINE NEW BUILD VERSION NUMBER (DON'T ALLOW DOUBLE-DIGITS)
	;
		StringSplit, v, INIVERSION, .
		
		if (v4 < 9)
			NEW_VERSION := setVersion(v1,v2,v3, v4 + 1)
		else if (v3 < 9)
			NEW_VERSION := setVersion(v1,v2,v3 + 1, 1)
		else if (v2 < 9)
			NEW_VERSION := setVersion(v1, v2 + 1, 1, 1)
		else
			NEW_VERSION := setVersion(v1 + 1, 1, 1, 1)
		

	
	;____________________________________
	; 	WRITE THE NEW VERSION TO PMAL INI
	;
		IniWrite, % NEW_VERSION, % PMAL_INI, version, File_Version
		IniWrite, 0, % PMAL_INI, version, Inc_File_Version
	
		
	
	;________________________________________
	; 	WRITE NEW VERSION TO PM INSTALLER INI
	;
		IniWrite, % NEW_VERSION, % INFILE_INI, Version, File_Version
		IniWrite, 0, % INFILE_INI, Version, Inc_File_Version
	




;============================================================================
;                   COMPILE & VERIFY PM APP LAUNCHER
;============================================================================
	
	
	
	;____________________________________________
	; 	DELETE EXISTING PM APP LAUNCHER EXE FILE
	;
		FileDelete, % PMAL
		Sleep 150
		
		
	
	;__________________________
	; 	COMPILE PM APP LAUNCHER
	;
		RunWait, C:\Program Files\autohotkey\compiler\compile_ahk.exe /nogui "%PMAL_AHK%"
		Sleep 600
	
	
	
	;___________________________________________________________________
	; 	MAKE SURE COMPILED PM APP LAUNCHER.EXE EXISTS & GET FILE VERSION
	;
		if !FileExist(PMAL){
			MsgBox Compiled PM App Launcher not found...
			ExitApp
		}
		FileGetVersion, PMALVER, % PMAL
	




;============================================================================
;               COMPILE & VERIFY  PM APP LAUNCHER INSTALLER
;============================================================================
	
	
	
	;_____________________________________
	; 	DELETE EXISTING INSTALLER EXE FILE
	;
		FileDelete, % INFILE
		Sleep 150
		
	
	
	
	;____________________________________
	; 	COMPILE PM APP LAUNCHER INSTALLER
	;
		RunWait, C:\Program Files\autohotkey\compiler\compile_ahk.exe /nogui "%INFILE_AHK%"
		Sleep 600
	
	
	

	
	
	
	
;============================================================================
;	              VERIFY PROPER BUILD  &  FILE  VERSIONING
;============================================================================
publish:


	;_________________________________________________
	; 	MAKE SURE INSTALLER EXE EXISTS AND GET VERSION
	;
		If !(FileExist(INFILE)){
			MsgBox Compiled installer file not found...
			ExitApp
		}
		FileGetVersion, INSTALLERVER, % INFILE
		
		
				
		
		
;============================================================================
;              PROMPT  ::   PUBLISH  UPDATE  FILE?
;============================================================================
	ans := custmsgbox("PM App Launcher Build", "Publish this update?","Yes - Publish|No - Run Local|No", "Q")
	
			
			
			
	;==============================
	;			PUBLISH BUILD
	;==============================
	If InStr(ans, "Yes")
	{
		
		;________________________________________________________________________
		; 	RUN VERSION UPDATER & VERIFY THAT INSTALLER IS SAME VERSION AS IN INI
		;
		RunWait, % VER_UPDATE
		Sleep 100
		IniRead, INIVERSION, % VERSION_INI, pm app launcher, version
		
		if (INSTALLERVER != INIVERSION){
			MsgBox, Installer (%INSTALLERVER%) and INI File (%INIVERSION%) versions are not the same...
			ExitApp
		}
		
		
		
		;_______________________
		; 	RUN DUMP SOURCE FILE
		;
		;~ RunWait, % DUMP_BUILD
		;~ Sleep 100
		
				
		
		
		;______________________________________________
		; 	DELETE EXISTING UPDATE FILE (IF APPLICABLE)
		;
		FileMove, % PUBLISHED_FILE, %PUBLISHED_FILE%.BAK, 1
		Sleep 100
		
	
		;____________________________________
		; 	MOVE UPDATE FILE TO PUBLIC FOLDER
		;
		FileMove, % INFILE, % PUBLISHED_FILE, 1
		if (ErrorLevel){
			MsgBox, Error occurred while trying to Move Installer to Public folder...
			ExitApp
		}
		
		
		;______________________________________
		; 	DELETE COMPILED PM APP LAUNCHER.EXE
		;
		Sleep 100		
		FileDelete, % PMAL
		Sleep 150



		
		;___________________________________________
		; 		EXIT IF RUNNING FROM -PUBLISH SWITCH
		;
		if p.publish
			ExitApp
			
	} else if Instr(ans, "Run Local"){
	
	
	
	;==============================
	;		RUN LOCALLY / TEST
	;==============================
		Process, Close, PM Application Launcher.exe
		Sleep 100
		
		;_______________________________________
		; 	BACKUP EXISTING PM APP LAUNCHER FILE
		;
		FileMove, %A_MyDocuments%\pm app launcher\pm application launcher.exe, %A_Mydocuments%\pm App Launcher\PM Application Launcher.exe.bak, 1
		Sleep 100
		
		;_____________________________________
		; 	COPY NEW FILE TO INSTALL DIRECTORY
		;
		FileCopy, % PMAL, %A_Mydocuments%\pm App Launcher\PM Application Launcher.exe, 1
		Sleep 100
		
		
		;___________________
		; 	RUN THE NEW FILE
		;
		run, %A_Mydocuments%\pm App Launcher\PM Application Launcher.exe
		Sleep 50
	}

		
		
		
;============================================================================
;        SUCCESS  --  FILE UPREVED, SOURCE DUMPED AND PUBLISHED
;============================================================================
	msgbox, 4160, PM App Launcher Update Publish
		,                                          Success!!`n`nUpdate version (%INSTALLERVER%) successfully  published.`n`nThe current AHK source files have been backed up to the \build folder`nwithin the main SVN repository.`n




;----------------
	Sleep 250
	ExitApp
;----------------




;==============================================================================
;                      SET  NEW VERSION FUNCTION
;==============================================================================
setVersion(_v1, _v2, _v3, _v4){
	return _v1 "." _v2 "." _v3 "." _v4
}





;=================================================================
;           RUNS NATURALDOCS ON PM APP LAUNCHER ROOT FOLDER.
;=================================================================
document(){
	SplashImage, , w375 h125 B1, , `nCompiling documentation`nPlease wait...., 
	
	RunWait, mkdoc, %A_ScriptDir%, Hide
	Sleep 100
	SplashImage, Off
	MsgBox, Documentation compile complete! `n`nPress OK to exit...
	ExitApp

}



;===================================================================================================
; Function: param
;
;		Handles parameters passed as argument strings & returns an array containing all parameter
;       switches and their values. 
;
;       Finds all key parameters marked with a dash (-) or slash (/), such as
;
;           > -path {some path}     OR
;           > /path {some path}
;
;		and assigns the array value {Object}.{Parameter Name} := {Parameter value}
;
; Parameters:
;		paramString - String of parameter arguments
;
; Returns:
;		Array of parameter values.
;
; Remarks:
;		If a key is found with no corresponding value, such as the key "run" in this example:
;				-run -move <path>
;		then the function will set it's value in the return array to 1. In the example, p.run = 1 (true)
;
; Examples:
;   (Start code)
;		paramList = -file "c:\windows\notepad.exe" -time 20
;
;       ;Call the function, passing the parameter string
;		p := params(paramList)
;
;       ;Display the values assigned to the object array
;		msgbox, % p.file
;		msgbox, % time.file
;
;		*Output*
;
;		Msgbox 1-
;
;			c:\windows\notepad.exe
;
;		Msgbox 2-
;
;			20
;   (End)
;===================================================================================================
param(p) {
    p := RegExReplace(p , "([^\s])-", "$1<dash>")   ; change - to <dash> to avoid confusion 
    regex = (?<=[-|/])([a-zA-Z0-9]*)[ |:|=|"]*([\w|.|@|?|#|$|`%|=|*|,|<|>|^|'|{|}|\[|\]|;|(|)|_|&|+| |:|!|~|/|\\]*)["| ]*(.*)
    
    count:=0
    options:=Object()
    
    while p != "" 
    {
        count++
        
        RegExMatch(p,regex,data) 
        
        name := data1
        value := data2
        value := RegExReplace(value , "<dash>", "-")   ; change <dash> back to -        
                
        if (value = "") {
            options[name] := 1
        } else {
            options[name] := value
        }
        
        p := data3
    }
    ErrorLevel := count 
    Return options
}







;-------------------------------------------------------------------------------
; Custom Msgbox
; Author  : Danny Ben Shitrit (aka Icarus)
;-------------------------------------------------------------------------------
; Copy this script or include it in your script (without the tester on top).
;
; Usage:
;   Answer := custmsgbox( title, text, buttons, icon="", owner=0 )
;   Where:
;     title   = The title of the message box.
;     text    = The text to display.
;     buttons = Pipe-separated list of buttons. Putting an asterisk in front of 
;               a button will make it the default.
;     icon    = If blank, we will use an info icon.
;               If a number, we will take this icon from Shell32.dll
;               If a letter ("I", "E" or "Q") we will use some predefined icons
;               from Shell32.dll (Info, Error or Question).
;     owner   = If 0, this will be a standalone dialog. If you want this dialog
;               to be owned by another GUI, place its number here.
;
;-------------------------------------------------------------------------------
custMsgBox( title, text, buttons, icon="", owner=0 ) {
  Global _CMsg_Result
  
  GuiID := 9      ; If you change, also change the subroutines below
  
  StringSplit Button, buttons, |
  
  If( owner <> 0 ) {
    Gui %owner%:+Disabled
    Gui %GuiID%:+Owner%owner%
  }

  Gui %GuiID%:+Toolwindow +AlwaysOnTop
  
  MyIcon := ( icon = "I" ) or ( icon = "" ) ? 222 : icon = "Q" ? 24 : icon = "E" ? 110 : icon
  
  Gui %GuiID%:Add, Picture, Icon%MyIcon% , Shell32.dll
  Gui %GuiID%:Add, Text, x+12 yp w180 r8 section , %text%
  
  Loop %Button0% 
    Gui %GuiID%:Add, Button, % ( A_Index=1 ? "x+12 ys " : "xp y+3 " ) . ( InStr( Button%A_Index%, "*" ) ? "Default " : " " ) . "w100 gCMsgButton", % RegExReplace( Button%A_Index%, "\*" )

  Gui %GuiID%:Show,,%title%
  
  Loop 
    If( _CMsg_Result )
      Break

  If( owner <> 0 )
    Gui %owner%:-Disabled
    
  Gui %GuiID%:Destroy
  Result := _CMsg_Result
  _CMsg_Result := ""
  Return Result
}


9GuiEscape:
9GuiClose:
  _CMsg_Result := "Close"
Return

CMsgButton:
  StringReplace _CMsg_Result, A_GuiControl, &,, All
Return


;===========================================================
;	Group: About
;		General script file information
;
;		- *Written By:* 	Rameen Bakhtiary
;		- *Last Modified:*	12/7/2011
;===========================================================